package com.example.controller;


import com.example.pojo.Machine;
import com.example.pojo.PageResult;
import com.example.pojo.Result;
import com.example.service.MachineService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 设备管理控制器
 */
@Slf4j
@RequestMapping("/machines")
@RestController
public class MachineController {

    @Autowired
    private MachineService machineService;

    /**
     * 查询所有设备 -GET http://localhost:8881/machines/allmachine
     * @return
     */
    @GetMapping("/allmachine")
    public Result list(){
        log.info("查询设备列表");
        List<Machine> machines = machineService.findAll();
        return Result.success(machines);
    }

    /**
     * 分页查询设备 -GET http://localhost:8881/machines?page=1&pageSize=10
     */
    @GetMapping
    public Result page(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer pageSize){
        log.info("分页查询设备，当前页码为：{}，每页记录数：{}",page,pageSize);
        PageResult pageResult = machineService.page(page, pageSize);
        return Result.success(pageResult);
    }


    /**
     * 根据设备id删除设备 -DELETE http://localhost:8881/machines?id=1
     * @param id
     * @return
     */
    @DeleteMapping
    public Result delete(Integer id) {
        log.info("根据id删除设备:{}",id);
        machineService.deleteById(id);
        return Result.success();
    }

    /**
     * 新增设备 -POST http://localhost:8881/machines
     */
    @PostMapping
    public Result save(@RequestBody Machine machine) {
        log.info("新增设备:{}",machine);
        machineService.save(machine);
        return Result.success();
    }

    /**
     * 根据id查询设备 -GET http://localhost:8881/machines/1
     */
    @GetMapping("/{machineID}")
    public Result getById(@PathVariable Integer machineID) {
        log.info("根据id查询设备:{}",machineID);
        Machine machine = machineService.getById(machineID);
        return Result.success(machine);
    }

    /**
     * 修改设备信息 -PUT http://localhost:8881/machines
     */
    @PutMapping
    public Result update(@RequestBody Machine machine) {
        log.info("修改设备信息:{}",machine);
        machineService.updata(machine);
        return Result.success();
    }

    /**
     * 获取所有设备isConnected  --GET http://localhost:8881/machines/isConnected
     */
    @GetMapping("/isConnected")
    public Result getAllIsConnected() {
        log.info("获取所有设备isConnected");
        return Result.success(machineService.getAllIsConnected());
    }


}
